﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace eStore.Models
{
    public class UserRepository:IUserRepository
    {
        private eStoreContainer _container = null;
        public UserRepository() {

            _container = new eStoreContainer();
        }

        public User GetUserByName(string sName)
        {
            var matchedUser = (from user in _container.Users
                               where user.UserName == sName
                               select user).FirstOrDefault();
            return matchedUser;
        }

        public IEnumerable<User> GetLatest(int? iTopLatest)
        {
            var intTop = iTopLatest??iTopLatest.Value;
            var allLatestUser = (from user in _container.Users.OrderByDescending(x => x.DateCreated)
                                 select user);
            var topLatestUSers = allLatestUser.Take(intTop);
            
            return topLatestUSers;
        }

        public void Add(User objT)
        {
            try
            {
                _container.Users.AddObject(objT);
                _container.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Remove(User objT)
        {
            try
            {
                _container.Users.DeleteObject(objT);
                _container.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }

        public void Update(User objT)
        {
            throw new NotImplementedException();
        }

        public User GetById(int iID)
        {
            var matchedUser = (from user in _container.Users
                               where user.UserId == iID
                               select user).FirstOrDefault();
            return matchedUser; 
        }

        public User GetById(string sID)
        {
            int iID = Int32.Parse(sID);
            return GetById(iID);
        }

        public IEnumerable<User> GetAll()
        {
            var allUsers = (from user in _container.Users
                            select user);
            return allUsers;
        }


        public ProductReview SubmitReview(ProductReview NewReview)
        {
            _container.ProductReviews.AddObject(NewReview);
            _container.SaveChanges();
            return NewReview;
        }
    }
}